#include <sys/wait.h>
#include <unistd.h>
#include "config.h"
#include "queue.h"
#include "cloud_msg.h"
#include "aliyun_proc.h"

config *g_conf = NULL;
int main()
{
	pid_t pid = fork();
	if (pid < 0) {
		exit(0);
	} else if (pid > 0) {
		sigset_t bset;
		sigfillset(&bset);
		sigprocmask(SIG_BLOCK, &bset, NULL);
		waitpid(pid, NULL, 0);
		cloud_offline();
		exit(0);
	}

	config cfg;
	g_conf = &cfg;
	if (g_conf->self["Devsecret"] == "") {
		char *dsec = NULL;
		if (dyn_register(g_conf->self["ProductionKey"].c_str(), g_conf->self["ProductionSecret"].c_str(), g_conf->self["DevName"].c_str(),
				 g_conf->self["AliyunHost"].c_str(), &dsec) == 0) {
			g_conf->self["Devsecret"] = dsec;
			ofstream os("/etc/aliynun_config/config.json", ios::trunc);
			os << cfg;
			os.close();
		} else {
			printf("dynamic register dev fail");
			exit(0);
		}
	}

	void *mqtt_handle =
		mqtt_start(g_conf->self["ProductionKey"].c_str(), g_conf->self["DevName"].c_str(), g_conf->self["Devsecret"].c_str(), g_conf->self["AliyunHost"].c_str());
	void *subdev_handle = subdev_proc_init(mqtt_handle);
	void *ota_handle = ota_proc_init(mqtt_handle, cfg.self["Version"].c_str());
	void *ra_hanle = ra_proc_init(mqtt_handle);
	if (!mqtt_handle || !subdev_handle || !ota_handle || !ra_hanle) {
		exit(0);
	}

	for (;;) {
		char msg[1024 * 8];
		if (recv_msg(CLOUD_QUEUE, msg, sizeof(msg)) > 0) {
			printf("recv msg:%s\n", msg);
			cloud_msg_proc(msg, mqtt_handle, subdev_handle);
		} else {
			perror("recv_msg");
		}
	}

	return 0;
}
